﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ObservadorPeplau.API.Business;

namespace ObservadorPeplau.API.Buffer
{
    public static class DiscussionBuffer
    {
        private const int BufferTimeMs = Constants.DiscussionBufferTimeMs;
        private static readonly List<BufferEntry> Discussions = new List<BufferEntry>();

        public static List<Comment> GetComments(string url)
        {
            // Return from buffer if not expired
            if (Discussions.Count(p=>p.DiscussionUrl==url)>0)
            {
                var bufferEntry = Discussions.First(p => p.DiscussionUrl == url);
                TimeSpan span = DateTime.Now.Subtract(bufferEntry.LastUpdate);

                // If buffer doesn't expired, return buffered discussion
                if (span.TotalMilliseconds <= BufferTimeMs)
                    return bufferEntry.Comments;
            }

            // Get from web in a new thread
            return GetCommentsNewThread(url);
        }

        private static List<Comment> GetCommentsNewThread(string url)
        {
            BufferEntry thisEntry;
            bool isNewEntry = true;

            // No discussion on buffer
            if (Discussions.Count(p => p.DiscussionUrl == url) > 0)
            {
                isNewEntry = false;
                thisEntry = Discussions.First(p => p.DiscussionUrl == url);
            }
            else
                thisEntry = new BufferEntry(url);

            // Get comments in a new thread
            var newThread = new Thread(delegate(object entry)
                                           {
                                               var myEntry = ((BufferEntry)entry);
                                               myEntry.Comments = DiscussionManager.GetCommentsFromWeb(myEntry.DiscussionUrl);
                                               myEntry.LastUpdate = DateTime.Now;
                                           }) {IsBackground = true};
            newThread.Start(thisEntry);
            Thread.Sleep(100);
            newThread.Join();
            
            // Add to buffer if needed
            if (isNewEntry)
                Discussions.Add(thisEntry);

            // Return from buffer
            return thisEntry.Comments;
        }
    }
}
